package user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xfengshopping.R;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import LOGIN.login;
import utils.TokenUtils;
import shoppingcart.fragment.CreateOrder;

public class AddressManagementActivity extends AppCompatActivity {
    private RecyclerView addressRecyclerView;
    private AddressAdapter addressAdapter;
    private List<Address> addressList = new ArrayList<>();
    private LinearLayout emptyState;
    private static final int REQUEST_ADD_ADDRESS = 1;
    private static final int REQUEST_EDIT_ADDRESS = 2;
    static final String API_URL = "http://47.99.134.126:28019/api/v1/address";
    private static final int UNAUTHORIZED = 401;

    // 使用 AtomicBoolean 确保只有一个网络请求在执行
    private AtomicBoolean isLoading = new AtomicBoolean(false);

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                updateUI();
            } else if (msg.what == UNAUTHORIZED) {
                handleUnauthorized();
            } else {
                showToast((String) msg.obj);
            }
        }
    };
    private View backButton;

    // ============= 新增内容开始 =============
    private static final String EXTRA_SELECT_MODE = "select_mode";
    private static final String EXTRA_CART_ITEM_IDS = "cart_item_ids";
    private boolean isSelectMode = false;
    private int[] cartItemIds;
    private OnAddressSelectedListener addressSelectedListener;

    public interface OnAddressSelectedListener {
        void onAddressSelected(Address address, int[] cartItemIds);//=============被修改============
    }
    // ============= 新增内容结束 =============

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_management);

        // ============= 新增内容开始 =============
        // 检查是否是选择模式
        isSelectMode = getIntent().getBooleanExtra(EXTRA_SELECT_MODE, false);
        if (isSelectMode) {
            setupSelectionMode();
        }
        // ============= 新增内容结束 =============

        initViews();
        initRecyclerView();
        setupAddAddressListener();
        setupEditAddressListener();
        checkLoginAndLoadAddresses();
    }

    // ============= 新增内容开始 =============
    // 设置选择模式
    private void setupSelectionMode() {
        cartItemIds = getIntent().getIntArrayExtra(EXTRA_CART_ITEM_IDS);
        if (cartItemIds == null) {
            cartItemIds = new int[0];
        }
        Log.d("AddressManagement", "选择模式初始化，购物车项: " + Arrays.toString(cartItemIds));

        addressSelectedListener = new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Address address, int[] cartItemIds) {
                Log.d("AddressManagement", "地址被选中: " + address.id + ", 购物车项: " + Arrays.toString(cartItemIds));
                saveOrder(address.id, cartItemIds, address); // 传递 address 作为第三个参数
            }
        };
    }


    public void saveOrder(int addressId, int[] cartItemIds, Address address) {
        Intent intent = new Intent(AddressManagementActivity.this, CreateOrder.class);
        intent.putExtra("addressId", addressId);
        intent.putExtra("cartItemIds", cartItemIds);

        if (address != null) {
            intent.putExtra("addressName", address.name);
            intent.putExtra("addressPhone", address.phone);
            intent.putExtra("addressDetail", address.address);
        }

        startActivity(intent);
        finish();
    }
    // ============= 新增内容结束 =============


    @Override
    protected void onResume() {
        super.onResume();
        checkLoginAndLoadAddresses();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_ADD_ADDRESS || requestCode == REQUEST_EDIT_ADDRESS)
                && resultCode == RESULT_OK) {
            checkLoginAndLoadAddresses();
        }
    }

    private void checkLoginAndLoadAddresses() {
        String token = TokenUtils.getToken(this);
        if (TextUtils.isEmpty(token)) {
            handleUnauthorized();
            return;
        }

        // 防止重复请求
        if (!isLoading.compareAndSet(false, true)) {
            Log.d("ADDRESS_ACTIVITY", "Already loading addresses, skipping request");
            return;
        }

        // 在加载新数据前清空列表
        addressList.clear();
        loadAddressesFromApi(token);
    }

    private void initViews() {
        addressRecyclerView = findViewById(R.id.address_list);
        emptyState = findViewById(R.id.empty_state);
        backButton = findViewById(R.id.back_button);
        findViewById(R.id.add_address_text);

        backButton.setOnClickListener(v -> finish());
    }

    private void setupAddAddressListener() {
        View addAddressBtn = findViewById(R.id.add_address_text);
        if (addAddressBtn != null) {
            addAddressBtn.setOnClickListener(v -> {
                Intent intent = new Intent(this, AddAddressActivity.class);
                startActivityForResult(intent, REQUEST_ADD_ADDRESS);
            });
        }
    }

    private void setupEditAddressListener() {
        // 无需单独初始化 Adapter，RecyclerView 初始化时已设置
    }

    private void initRecyclerView() {
        if (addressRecyclerView == null) {
            Log.e("ADDRESS_ACTIVITY", "RecyclerView 未找到，结束页面");
            finish();
            return;
        }
        addressRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        addressAdapter = new AddressAdapter(addressList);
        addressRecyclerView.setAdapter(addressAdapter);
    }

    private void loadAddressesFromApi(String token) {
        new Thread(() -> {
            HttpURLConnection conn = null;
            try {
                URL url = new URL(API_URL);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("token", token);
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    String response = readInputStream(conn.getInputStream());
                    parseAddressResponse(response);
                } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    handler.sendEmptyMessage(UNAUTHORIZED);
                } else {
                    String errorMessage = readErrorStream(conn);
                    handler.obtainMessage(0, errorMessage).sendToTarget();
                }
            } catch (Exception e) {
                e.printStackTrace();
                handler.obtainMessage(0, "网络请求失败").sendToTarget();
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
                // 重置加载状态
                isLoading.set(false);
            }
        }).start();
    }

    private void parseAddressResponse(String response) {
        // 创建临时列表以避免竞态条件
        List<Address> tempList = new ArrayList<>();

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getInt("resultCode") == 200) {
                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    String fullAddress = item.getString("provinceName") +
                            item.getString("cityName") +
                            item.getString("regionName") +
                            item.getString("detailAddress");

                    tempList.add(new Address(
                            item.getInt("addressId"),
                            item.getString("userName"),
                            item.getString("userPhone"),
                            fullAddress,
                            item.getInt("defaultFlag") == 1
                    ));
                }

                // 在主线程更新列表
                handler.post(() -> {
                    addressList.clear();
                    addressList.addAll(tempList);
                    updateUI();
                });
            } else {
                handler.obtainMessage(0, jsonObject.getString("message")).sendToTarget();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            handler.obtainMessage(0, "数据解析失败").sendToTarget();
        }
    }

    private String readInputStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }

    private String readErrorStream(HttpURLConnection conn) throws IOException {
        if (conn.getErrorStream() != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            StringBuilder errorResponse = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                errorResponse.append(line);
            }
            reader.close();
            return errorResponse.toString();
        }
        return "请求失败（错误码：" + conn.getResponseCode() + "）";
    }

    private void updateUI() {
        runOnUiThread(() -> {
            addressAdapter.notifyDataSetChanged();
            emptyState.setVisibility(addressList.isEmpty() ? View.VISIBLE : View.GONE);
        });
    }

    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    private void handleUnauthorized() {
        runOnUiThread(() -> {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            TokenUtils.clearToken(this);
            startActivity(new Intent(this, login.class));
            finish();
        });
    }

    public class AddressAdapter extends RecyclerView.Adapter<AddressViewHolder> {
        private final List<Address> addressList;

        public AddressAdapter(List<Address> addressList) {
            this.addressList = addressList;
        }

        @NonNull
        @Override
        public AddressViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.item_address, parent, false);
            return new AddressViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull AddressViewHolder holder, int position) {
            Address addr = addressList.get(position);
            holder.nameText.setText(addr.name);
            holder.phoneText.setText(addr.phone);
            holder.addressText.setText(addr.address);
            holder.defaultTag.setVisibility(addr.isDefault ? View.VISIBLE : View.GONE);

            // ============= 新增内容开始 =============
            // 修改：根据模式设置不同的点击行为
            holder.itemView.setOnClickListener(v -> {
                if (isSelectMode && addressSelectedListener != null) {
                    // 修改这里，添加cartItemIds参数
                    addressSelectedListener.onAddressSelected(addr, cartItemIds);
                } else {
                    // 原有编辑逻辑
                    Intent intent = new Intent(AddressManagementActivity.this, AddressEditActivity.class);
                    intent.putExtra("address", addr);
                    startActivityForResult(intent, REQUEST_EDIT_ADDRESS);
                }
            });
            // ============= 新增内容结束 =============

            holder.editIcon.setOnClickListener(v -> {
                Intent intent = new Intent(AddressManagementActivity.this, AddressEditActivity.class);
                intent.putExtra("address", addr);
                startActivityForResult(intent, REQUEST_EDIT_ADDRESS);
            });
        }

        @Override
        public int getItemCount() {
            return addressList.size();
        }
    }

    public static class AddressViewHolder extends RecyclerView.ViewHolder {
        TextView nameText, phoneText, addressText, defaultTag;
        ImageView editIcon;

        public AddressViewHolder(@NonNull View itemView) {
            super(itemView);
            nameText = itemView.findViewById(R.id.name_text);
            phoneText = itemView.findViewById(R.id.phone_text);
            addressText = itemView.findViewById(R.id.address_text);
            defaultTag = itemView.findViewById(R.id.default_tag);
            editIcon = itemView.findViewById(R.id.edit_icon);
        }
    }
}
